<template>
  <view class="group-buying-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-center-only">
        <text class="nav-title">拼单中</text>
      </view>
    </view>
    
    <!-- 拼单列表 -->
    <scroll-view class="group-list" scroll-y>
      <view 
        class="group-item" 
        v-for="(item, index) in groupBuyingList" 
        :key="index"
        @click="handleGroupClick(item)"
      >
        <!-- 左侧菜品图片 -->
        <view class="food-image">
          <image 
            :src="item.foodImage" 
            mode="aspectFill"
            class="food-img"
          />
        </view>
        
        <!-- 中间信息区域 -->
        <view class="group-info">
          <!-- 菜品名称 -->
          <text class="food-name">{{ item.foodName }}</text>
          
          <!-- 店名 -->
          <text class="store-name">{{ item.storeName }}</text>
          
          <!-- 用户头像列表 -->
          <view class="user-avatars">
            <view 
              class="avatar-item" 
              v-for="(user, userIndex) in item.participants" 
              :key="userIndex"
            >
              <image 
                :src="user.avatar" 
                mode="aspectFill"
                class="user-avatar"
              />
            </view>
            <!-- 如果还有空位，显示占位符 -->
            <view 
              class="avatar-placeholder" 
              v-for="n in (item.maxParticipants - item.participants.length)"
              :key="'placeholder-' + n"
            >
              <text class="placeholder-text">+</text>
            </view>
          </view>
        </view>
        
        <!-- 右侧信息 -->
        <view class="group-right">
          <!-- 拼单状态 -->
          <view class="group-status">
            <text class="status-text">拼单中{{ item.participants.length }}/{{ item.maxParticipants }}</text>
          </view>
          
          <!-- 价格 -->
          <view class="price-section">
            <text class="price">¥{{ item.price }}</text>
          </view>
          
          <!-- 立即拼单按钮 -->
          <view class="join-btn" @click.stop="joinGroupBuy(item)">
            <text class="btn-text">立即拼单</text>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="groupBuyingList.length === 0">
        <text class="empty-text">暂无拼单活动</text>
        <text class="empty-desc">快去首页发起拼单吧~</text>
      </view>
    </scroll-view>
  </view>
  
  <!-- 底部导航栏 -->
  <view class="bottom-nav">
    <view class="nav-item" @click="goHome">
      <text class="nav-icon">🏠</text>
      <text class="nav-label">首页</text>
    </view>
    <view class="nav-item active" @click="goGroupBuying">
      <text class="nav-icon">👥</text>
      <text class="nav-label">拼单</text>
    </view>
    <view class="nav-item" @click="goOrders">
      <text class="nav-icon">📦</text>
      <text class="nav-label">订单</text>
    </view>
    <view class="nav-item" @click="goProfile">
      <text class="nav-icon">👤</text>
      <text class="nav-label">我的</text>
    </view>
  </view>
</template>

<script>
import groupBuyingService from '../../services/group-buying.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      loading: false,
      groupBuyingList: [], // 移除静态数据
      page: 1,
      pageSize: 20,
      hasMore: true,
      isFirstLoad: true  // 标记是否首次加载
    }
  },
  
  onLoad(options) {
    this.getStatusBarHeight()
    this.loadGroupBuyingList()
    this.isFirstLoad = true
  },
  
  onShow() {
    // 页面显示时刷新列表（可能从详情页返回）
    // 避免首次加载时重复请求
    if (!this.isFirstLoad) {
      console.log('从其他页面返回，刷新拼单列表')
      this.loadGroupBuyingList(true)
    } else {
      this.isFirstLoad = false
    }
  },
  
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },
    
    // 加载拼单列表
    async loadGroupBuyingList(refresh = false) {
      if (this.loading) return
      
      // 如果是刷新，重置分页
      if (refresh) {
        this.page = 1
        this.hasMore = true
        this.groupBuyingList = []
      }
      
      // 如果没有更多数据，不再请求
      if (!this.hasMore && !refresh) return
      
      this.loading = true
      
      try {
        console.log('加载拼单列表 - 页码:', this.page)
        
        // 调用拼单列表API，只获取活跃的拼单
        const response = await groupBuyingService.getActivityList({
          status: 'active',
          page: this.page,
          limit: this.pageSize
        })
        
        console.log('拼单列表响应:', response)
        
        const activities = response?.data?.activities || response?.data || []
        
        // 格式化数据
        const formattedList = activities.map(act => {
          const formatted = groupBuyingService.formatActivityForList(act)
          
          // ✅ 使用后端返回的真实参与者数据
          if (act.participants && act.participants.length > 0) {
            // 过滤掉已取消的参与者（status = 'cancelled'）
            formatted.participants = act.participants
              .filter(p => p.status !== 'cancelled')  // ⭐ 过滤已取消的
              .map(p => ({
                id: p.id,
                userId: p.userId || p.user_id,
                name: p.realName || p.username || '用户',
                avatar: p.avatar || '/static/avatar.jpg',
                status: p.status
              }))
          } else {
            // 如果后端没返回参与者数据，使用空数组
            formatted.participants = []
          }
          
          return formatted
        })
        
        if (refresh) {
          this.groupBuyingList = formattedList
        } else {
          this.groupBuyingList = [...this.groupBuyingList, ...formattedList]
        }
        
        // 判断是否还有更多数据
        this.hasMore = formattedList.length >= this.pageSize
        this.page++
        
        console.log('拼单列表加载成功，共', this.groupBuyingList.length, '条')
      } catch (error) {
        console.error('加载拼单列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 处理拼单项点击
    handleGroupClick(item) {
      // 跳转到拼单详情页
      uni.navigateTo({
        url: `/pages/group-buying-detail/group-buying-detail?id=${item.id}`
      })
    },
    
    // 加入拼单（点击"立即拼单"按钮）
    async joinGroupBuy(item) {
      // 检查登录
      const token = uni.getStorageSync('jwt_token')
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 1500)
        return
      }
      
      // 跳转到拼单详情页（让用户确认后再参与）
      this.handleGroupClick(item)
    },
    
    // 底部导航按钮
    goHome() {
      uni.redirectTo({ url: '/pages/home/home' })
    },
    goGroupBuying() {
      // 已经在拼单页，不执行跳转
      return
    },
    goOrders() {
      uni.redirectTo({ url: '/pages/orders/orders' })
    },
    goProfile() {
      uni.redirectTo({ url: '/pages/profile/profile' })
    }
  }
}
</script>

<style lang="scss" scoped>
.group-buying-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background: #fff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  z-index: 998;
  
  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    
    .back-icon {
      font-size: 36rpx;
      color: #333;
      font-weight: bold;
    }
  }
  
  .nav-center {
    flex: 1;
    text-align: center;
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .nav-center-only {
    width: 100%;
    text-align: center;
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .nav-right {
    width: 60rpx;
  }
}

.group-list {
  flex: 1;
  margin-top: calc(var(--status-bar-height) + 88rpx);
  padding: 20rpx;
}

.group-item {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s ease;
  
  &:active {
    transform: scale(0.98);
  }
  
  .food-image {
    width: 140rpx;
    height: 140rpx;
    margin-right: 30rpx;
    
    .food-img {
      width: 100%;
      height: 100%;
      border-radius: 12rpx;
      background: #f0f0f0;
    }
  }
  
  .group-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 140rpx;
    margin-right: 20rpx;
    
    .food-name {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .store-name {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 20rpx;
    }
    
    .user-avatars {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 6rpx;
      
      .avatar-item {
        .user-avatar {
          width: 52rpx;
          height: 52rpx;
          border-radius: 50%;
          background: #f0f0f0;
        }
      }
      
      .avatar-placeholder {
        width: 52rpx;
        height: 52rpx;
        border-radius: 50%;
        background: #f0f0f0;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .placeholder-text {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
  
  .group-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: space-between;
    height: 140rpx;
    min-width: 120rpx;
    
    .group-status {
      .status-text {
        font-size: 24rpx;
        color: #ff4757;
        font-weight: 600;
      }
    }
    
    .price-section {
      .price {
        font-size: 32rpx;
        font-weight: 700;
        color: #ff4757;
      }
    }
    
    .join-btn {
      background: #ff4757;
      border-radius: 20rpx;
      padding: 12rpx 24rpx;
      cursor: pointer;
      transition: background 0.3s ease;
      
      &:active {
        background: #ff3742;
      }
      
      .btn-text {
        font-size: 24rpx;
        color: #fff;
        font-weight: 600;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 16rpx;
  }
  
  .empty-desc {
    font-size: 26rpx;
    color: #ccc;
  }
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
  
  .nav-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    padding: 12rpx 0;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    
    &:active {
      transform: scale(0.95);
    }
    
    .nav-icon {
      font-size: 44rpx;
      transition: all 0.3s ease;
      filter: grayscale(100%);
      opacity: 0.6;
    }
    
    .nav-label {
      font-size: 22rpx;
      color: #999;
      font-weight: 500;
      transition: all 0.3s ease;
    }
    
    /* 选中状态 */
    &.active {
      .nav-icon {
        filter: grayscale(0%);
        opacity: 1;
        transform: scale(1.1);
      }
      
      .nav-label {
        color: #667eea;
        font-weight: 600;
      }
      
      /* 选中指示器 */
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 3rpx;
      }
    }
  }
}
</style>
